
local plugin_name = ({...})[1]:match("^kong%.plugins%.([^%.]+)")
-- local plugin = require "kong.plugins.plugin-manage.plugin"
local plugin = require("kong.plugins." .. plugin_name .. ".plugin")
-- local tools = require "kong.plugins.plugin-manage.tools"
local tools = require("kong.plugins." .. plugin_name .. ".tools")
local kong = kong
local cjson_safe = require "cjson.safe"


--- 校验路径是否合法
-- @param file_path 待校验文件路径
local function is_legal(file_path)
  return string.find(file_path, [[^/[%w_/%-%*]+/$]]) or file_path == "/"
end


--- 发送响应
local function send_response(code, msg)
  local res = {}
  res["code"] = code
  res["message"] = msg

  kong.response.exit(plugin.HTTP_OK,res)
end

--- 管理接口
-- @param file_path 文件路径
-- @param file_name 文件名
-- @param file_code 文件内容
return {
  ["/conf_manage/push"] = {
    POST = function(self)
      local conf_detail = self.params.conf_detail or nil
      
      -- 非空判断
      if not tools.is_present(conf_detail) then
        local msg = "配置为空，配置校验不通过"
        send_response(plugin.HTTP_BAD_REQUEST, msg)
      end

      local code, msg = plugin.update_conf(conf_detail)

      send_response(code, msg)
    end
  },

  ["/conf_manage/version_detail"] = {
    GET = function(self)
      local conf_version = self.params.conf_version or nil

      -- 非空判断
      if not tools.is_present(conf_version) then
        local msg = "配置版本为空，配置版本校验不通过"
        send_response(plugin.HTTP_BAD_REQUEST, msg)
      end

      local code, msg = plugin.version_detail(conf_version)

      send_response(code, msg)
    end
  },
  ["/conf_manage/delete"] = {
    DELETE = function(self)
      local conf_version = self.params.conf_version or nil

      -- 非空判断
      if not tools.is_present(conf_version) then
        local msg = "配置版本为空，配置版本校验不通过"
        send_response(plugin.HTTP_BAD_REQUEST, msg)
      end

      local code, msg = plugin.delete_conf(conf_version)

      send_response(code, msg)
    end
  },
  ["/conf_manage/list_versions"] = {
    GET = function(self)
      local code, msg = plugin.list_versions()
      send_response(code, msg)
    end
  }
}

